package com.davy.gridpoint.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.http.CommonHttpConsts;
import com.davy.gridpoint.http.HttpCallbackData;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.qlxj.TakeActivity;
import com.davy.gridpoint.qlxj.adapter.ImgAdapter;
import com.davy.gridpoint.utils.DialogUitl;
import com.davy.gridpoint.utils.GPSToGCJ;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.CustomImageView;
import com.davy.gridpoint.view.MyRecyclerView;
import com.google.gson.Gson;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PointActivity extends BaseActivity {
    private static final int REQUEST_LOCATION_PERMISSION_CODE = 1;
    private final int REQUEST_IMG = 1001;
    private Activity mActivity;
    private TextView tvTitle, GeoGridName;
    private RadioGroup groupType, groupLc;
    private RadioButton radioLc1, radioLc2;
    private AppCompatButton btnConfirm;
    protected LocationManager locationManager;
    private String mLongitude, mLatitude;
    protected DecimalFormat decimalFormat;
    protected DecimalFormat decimalFormat2;
    private Map<String, Object> dataMap;

    private MyRecyclerView recyclerImg;
    private ImgAdapter imgAdapter;
    private ArrayList<Map> imgList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point);
        mActivity = this;
        dataMap = new HashMap<>();
        imgList = new ArrayList<>();
        decimalFormat = new DecimalFormat("#.000000");
        decimalFormat2 = new DecimalFormat("#.00");
        statusbar4();
        initView();
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
        } else {
            LogUtils.e("TAG", "权限已经授予");
            // 权限已经授予，可以进行位置相关的操作
            initLocation();
        }
    }

    private String inType = "";
    private String inLc = "";

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("里程打卡");
        dataMap = (Map<String, Object>) getIntent().getSerializableExtra("dataMap");
        LogUtils.e("TAG", "dataMap:" + dataMap.toString());
        GeoGridName = findViewById(R.id.GeoGridName);
        groupLc = findViewById(R.id.groupLc);
        groupType = findViewById(R.id.groupType);
        recyclerImg = findViewById(R.id.recyclerImg);
        radioLc1 = findViewById(R.id.radioLc1);
        radioLc2 = findViewById(R.id.radioLc2);
        btnConfirm = findViewById(R.id.btnConfirm);

        if (!dataMap.isEmpty()) {
            GeoGridName.setText(dataMap.get("GeoGridName") + "");
            radioLc1.setText("开始 " + dataMap.get("GeoStartMilege"));
            radioLc2.setText("结束 " + dataMap.get("GeoEndMilege"));
        }
        groupLc.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radioLc1:
                    if (!dataMap.isEmpty()) {
                        inLc = dataMap.get("GeoStartMilege") + "";
                    }
                    break;
                case R.id.radioLc2:
                    if (!dataMap.isEmpty()) {
                        inLc = dataMap.get("GeoEndMilege") + "";
                    }
                    break;
            }
        });
        groupType.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radioType1:
                    inType = "上行";
                    break;
                case R.id.radioType2:
                    inType = "下行";
                    break;
                case R.id.radioType3:
                    inType = "单线";
                    break;
                case R.id.radioType4:
                    inType = "双线";
                    break;
            }
        });

        recyclerImg.setLayoutManager(new GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false));
        imgAdapter = new ImgAdapter(mContext, imgList);
        recyclerImg.setAdapter(imgAdapter);
        imgAdapter.setItemClickListener(new ImgAdapter.ItemClickListener() {
            @Override
            public void addClick(int position) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                Intent intent = new Intent(mContext, TakeActivity.class);
                startActivityForResult(intent, REQUEST_IMG);
            }

            @Override
            public void delClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                imgList.remove(position);
                imgAdapter.setData(imgList);
            }

            @Override
            public void getClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                int type = Double.valueOf(StringUtils.isEmpty(mList.get("type") + "") ? "0" : mList.get("type") + "").intValue();
                if (type == 1 || type == 2) {
                    String img = mList.get("img") + "";
                    Double isBt = 1.0; //1：保存 2：提交
                    if (mList.containsKey("isBt")) {
                        isBt = Double.valueOf(mList.get("isBt") + "");
                    }

                    if (isBt.intValue() == 2) {
                        if (!img.startsWith("http")) {
                            img = HttpClient.imgUrl + img.replace("/storage/emulated/0/Davy/", "");
                        }
                    }

                    imgDialog(img);
                }
            }
        });

        btnConfirm.setOnClickListener(v -> {
            if (dataMap.isEmpty()) {
                ToastUtil.show("数据异常，请返回重试！");
                return;
            }
            if (StringUtils.isEmpty(inLc)) {
                ToastUtil.show("请选择里程信息！");
                return;
            }
            if (StringUtils.isEmpty(inType)) {
                ToastUtil.show("请选择行别！");
                return;
            }
            if (imgList.isEmpty()) {
                ToastUtil.show("请添加图片！");
                return;
            }
            if (StringUtils.isFastClick()) {
                return;
            }
            List<String> fileName = new ArrayList<>();
            List<File> files = new ArrayList<>();
            int i = 0;
            while (imgList.size() > i) {
                File file = new File(imgList.get(i).get("img").toString().trim());
                if (file.isFile()) {
                    files.add(file);
                    fileName.add(file.getName());
                }
                i++;
            }

            Map<String, Object> gridMap = new HashMap<>();
            if (!dataMap.isEmpty()) {
                gridMap.put("wgid", dataMap.get("ID"));
                gridMap.put("pws_id", dataMap.get("PwsId"));
                gridMap.put("pws_name", dataMap.get("PwsName"));
                gridMap.put("line_id", dataMap.get("LineId"));
                gridMap.put("line_name", dataMap.get("LineName"));
                gridMap.put("imei", dataMap.get("IMEI"));
                gridMap.put("cj_name", dataMap.get("YEAR"));
                gridMap.put("geo_grid_name", dataMap.get("GeoGridName"));
                gridMap.put("geo_end_milege", dataMap.get("GeoEndMilege"));
                gridMap.put("geo_start_milege", dataMap.get("GeoStartMilege"));
                gridMap.put("xb", dataMap.get("XbName"));
                gridMap.put("rail_leader_name", dataMap.get("RailLeaderName"));
                gridMap.put("rail_leader_phone", dataMap.get("RailLeaderPhone"));
                gridMap.put("level_name", dataMap.get("LevelName"));
                gridMap.put("longitude", mLongitude);
                gridMap.put("latitude", mLatitude);
                //gridMap.put("img_path", fileName);
            }

            GridPoint(gridMap, fileName, files);
        });
    }

    private void GridPoint(Map gridMap, List<String> fileName, List<File> files) {
        String json = new Gson().toJson(gridMap);
        LogUtils.e("TAG", "json:" + json);
        LogUtils.e("TAG", "fileName:" + fileName.toString());

        HttpClient.getInstance().postData(CommonHttpConsts.GridPoint, "GridPoint")
                .params("json", json)
                .addUrlParams("file_name", fileName)
                .addFileParams("file", files)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.showNew(mContext, msg);
                        if (code == 200) {
                            finish();
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.showNew(mContext, StringUtils.error_context);
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    public void imgDialog(String milepostStr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_img_item, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        CustomImageView imgYu1 = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(mContext).load(milepostStr).error(R.mipmap.icon_error).into(imgYu1);

        tvClose.setOnClickListener(v1 -> dialog.dismiss());
    }

    public void imgBack(View view) {
        finish();
    }

    private void initLocation() {
        if (locationManager != null) {
            locationManager = null;
        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider = "";
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        }
        // 检查权限和服务是否可用
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.v("TAG", "有没有权限");
                return;
            }
            LogUtils.v("TAG", "有权限，开始吧" + locationProvider);
            //LocationManager.NETWORK_PROVIDER  网络
            //LocationManager.GPS_PROVIDER  GPS
            locationManager.requestLocationUpdates(locationProvider, 1000, 0, locationListener);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locationListener);
        } else {
            LogUtils.v("TAG", "GPS is disabled");
        }
    }

    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 使用经纬度
            mLongitude = decimalFormat.format(location.getLongitude());
            mLatitude = decimalFormat.format(location.getLatitude());

            LogUtils.v("TAG", "经纬度：" + mLongitude + " " + mLatitude);

            GPSToGCJ.getAddress(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            // 用户启用GPS时调用
            LogUtils.v("TAG", "onProviderEnabled：" + provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // 用户禁用GPS时调用
            LogUtils.v("TAG", "onProviderDisabled：" + provider);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以进行位置相关的操作
                initLocation();
            } else {
                // 权限被拒绝，可以提示用户手动开启权限或进行其他处理
                ToastUtil.show("定位权限授权失败");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMG) {
                Bundle extras = data.getExtras();
                Map dataMap = new HashMap();
                dataMap.put("isBt", 1);//1：未提交 2：提交
                dataMap.put("p_time", StringUtils.getTimeS());
                dataMap.put("img", extras.get("data"));
                dataMap.put("type", 1);
                imgList.add(dataMap);
                imgAdapter.setData(imgList);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (locationManager != null) locationManager.removeUpdates(locationListener);
    }
}
